package com.ccg.securityConfig;

import com.ccg.entity.Message;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//登陆账户密码验证失败处理器,返回一个json对象,用于异步处理
@Component
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {

    private ObjectMapper objectMapper=new ObjectMapper();
    /**
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException{
        Message message;
        String str;
        if(e instanceof LockedException)
            str = "该账号被冻结无法登录";
        else if(e instanceof CheckCodeException)
            str = e.getMessage();
        else str = "账号或者密码错误";
        //System.out.println(e);
//        if(e instanceof CheckCodeException){
//            message  = new Message(1,"登陆失败",e.getMessage());
//        }
//        else
        message  = new Message(2,"登陆失败",str);
        String json = objectMapper.writeValueAsString(message);
        httpServletResponse.setContentType("application/json;charset=utf-8");
        httpServletResponse.getWriter().write(json);
    }
}